<template>
  <div class="tariffCont" curpage="tariffCont3234324234234">
    <layoutContent>
      <template #left v-if="props.type != 'foodGoods'">
        <div class="left_tree">
          <div class="title">{{ $t(`merak.${props.type}`) }}</div>
          <el-input
            v-model="treeState.filter"
            :placeholder="$t('merak.placeholder_filter')"
            :suffix-icon="Search"
            @input="value => treeRef?.filter(value)"
          />
          <div class="tree-wrapper">
            <el-scrollbar height="calc(100vh - 220px)" v-if="initTreeBool">
              <el-tree
                class="merakTree"
                ref="treeRef"
                node-key="id"
                :data="treeState.data"
                :props="{ children: 'childs' }"
                :default-expanded-keys="expandedKeys"
                :default-checked-keys="defaultKeys"
                :filter-node-method="(value, tree) => tree.label.includes(value)"
                @current-change="handleCurrentChange"
              />
            </el-scrollbar>
          </div>
        </div>
      </template>
      <template #search>
        <serachBar
          ref="searchBarRef"
          custom_class="myclass"
          :placeholder="$t('goods_tariff.tariff_code_placer')"
          v-model="searchformData"
          @searchEvent="searchFn"
          :closePlan="true"
        >
          <template #footer>
            <!-- -->

            <el-button type="primary" v-auth="{'authArr':paramsProp.authArr,'key':'add'}"  @click="onTariffPlus">{{$t('goods_tariff.add_tariff')}}</el-button>
            <el-button type="primary" plain v-auth="{'authArr':paramsProp.authArr,'key':'add'}"  @click="tariffTemplateFile">{{$t('goods_tariff.export_templete')}}</el-button>
          </template>

          <!-- 高级搜索弹出框 插槽-->
          <template #searchForm="searchProp">
            <!--  高级搜索弹出框内容-->
            <div class="modal-content">
              <!-- 高级搜索 -->
              <div class="modal-title">
                <!-- {{ $t(`merak.search_list_ad`) }} -->
              </div>

              <div class="modal—body">
                <el-scrollbar height="100%">
                  <div class="scrollbar-content">
                    <!-- 已选参数 组件-->
                    <selectedParams v-model="searchformData" label="label" val="value"></selectedParams>

                    <!-- 表单 :rules="searchformRules"-->
                    <el-form :model="searchformData" label-position="top" ref="searchFormRef" curpagename="stererwe5352">
                      <el-row :gutter="40">
                        <el-col :span="langEnv" v-for="(sItem, sIndex) in searchformData" :key="sIndex">
                          <el-form-item :label="sItem.label" v-if="sItem.type == 'select'" prop="sItem.value">
                            <el-select class="qf_select" v-model="sItem.value" filterable>
                              <el-option :label="item.label" :value="item.value" v-for="item in sItem.options" :key="item" />
                            </el-select>
                          </el-form-item>

                          <el-form-item :label="sItem.label" v-if="sItem.type == 'input'" prop="sItem.value">
                            <el-input class="qf_input" v-model="sItem.value" />
                          </el-form-item>
                        </el-col>
                      </el-row>
                    </el-form>
                    <!-- 表单 -->
                  </div>
                </el-scrollbar>
              </div>
              <div class="modal-footer">
                <!-- 取消 -->
                <el-button type="default" @click="closeModal">{{ $t("merak.reset") }}</el-button>
                <!-- 搜索 -->
                <el-button type="primary" @click="submitForm(searchFormRef)">{{ $t("merak.search") }}</el-button>
                <!-- 保存搜索方案 -->
                <el-button plain type="primary" v-if="searchProp.closePlan" @click="showPlanModal">
                  {{ $t("merak.save_search_scheme") }}
                </el-button>
              </div>
            </div>
            <!--  高级搜索弹出框内容-->
          </template>
          <!-- /高级搜索弹出框 插槽-->
        </serachBar>
      </template>
      <template #content>
        <tariffTable v-if="!initDataBool" v-bind="paramsProp" @editData="editDataFun" @delLine="delLineFun" @editCopyData="editCopyDataFun" @batchDelLine=batchDelLineFun></tariffTable>
      </template>
    </layoutContent>
    <div v-if="tariffShow">
      <addTariff
        :drawerTariff="drawerTariff"
        :editId="editId"
        :typeId="paramsProp.typeId"
        :editNum="editNum"
        @drawerClose="drawerCloseFun"
        @saveSuccess="saveSuccess"
      ></addTariff>
    </div>
    <div>
      <tariffTemplate
        :dialogTariff="dialogTariff"
        :typeId="paramsProp.typeId"
        @drawerCloseDialog="drawerCloseDialog"
      ></tariffTemplate>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { Search } from "@element-plus/icons-vue";
import { ref, reactive, computed, onMounted, watch, nextTick, getCurrentInstance } from "vue";
import layoutContent from "@/components/LayoutComponents/index.vue";
import { getTariffTreeApi, getTariffDelApi,getTariffSearchItemApi,getTariffBathDelApi } from "@/api/modules/goodsArchive/tariff/tariff";
import { ResultEnum } from "@/enums/httpEnum";
import { ElInput, ElScrollbar, ElTree, ElTabs, ElTabPane } from "element-plus";
import { useRoute } from "vue-router";
import serachBar from "@/components/SearchBar/index";
import selectedParams from "@/components/SearchBar/components/selectedParams.vue";
import tariffTable from "./tariffTable.vue";
import addTariff from "./tariffAdd.vue";
import tariffTemplate from "./tariffTemplate.vue";
import {typeObj} from "./tariffFormat";
import {
  moreConfirm,
  confirmWarningMsg,
  successMsg,
  warnMsg,
  failMsg,
  confirmSuccessMsg,
  delConfimMsg
} from "@/utils/messageUtils";
const { proxy } = getCurrentInstance();
const props = defineProps<{
  type?: string;
}>();
// key_words
const paramsProp = reactive({
  authArr:[],
  type: props.type,
  typeId: "",
  params: props.type == "foodGoods" ? { hs_code_cn: "" } : { hs_code: "" }
});
const langEnv = proxy.$t("lang") == "ru" ? 8 : 6;
const initDataBool = ref(true);
const route = useRoute();
//树结构
const initTreeBool=ref(false);
const treeRef = ref<InstanceType<typeof ElTree>>();

//权限
// const authList=ref({});
//#region 添加税则
//添加税则
const editId = ref("");
const editNum = ref("");
const tariffShow = ref(false);
const drawerTariff = ref(false);
const onTariffPlus = () => {
  tariffShow.value = true;
  editId.value = "";
  editNum.value = "add";
  setTimeout(() => {
    drawerTariff.value = true;
  }, 50);
};
//关闭
const drawerCloseFun = () => {
  tariffShow.value = false;

  setTimeout(() => {
    drawerTariff.value = false;
  }, 50);
};
//保存成功
const saveSuccess = () => {
  initDataBool.value = true;
  nextTick(() => {
    initDataBool.value = false;
  });
};

 
//编辑
const editDataFun = rows => {
  // let key = `tariff_${typeObj[paramsProp.typeId]}_id`;
  let key='id';
  editId.value = rows[key];
  tariffShow.value = true;
  editNum.value = "edit";
  setTimeout(() => {
    drawerTariff.value = true;
  }, 50);
};

const editCopyDataFun=rows=>{
    let key='id';
    // let key = `tariff_${typeObj[paramsProp.typeId]}_id`;
  editId.value = rows[key];
  tariffShow.value = true;
  editNum.value = "copy";
  setTimeout(() => {
    drawerTariff.value = true;
  }, 50);
}

//删除
const delLineFun = rows => {
  // let key = `tariff_${typeObj[paramsProp.typeId]}_id`;
    let key='id';
  let delId = rows[key];
  delConfimMsg({
    callback: val => {
      if (val == "confirm") {
        getTariffDelApi({ type_id: paramsProp.typeId, id: delId }).then(res => {
          if (res.code == ResultEnum.SUCCESS) {
            successMsg(proxy.$t("merak.delete_success"));
            initDataBool.value = true;
            nextTick(() => {
              initDataBool.value = false;
            });
          }
          if (res.code == ResultEnum.ERROR) {
            failMsg(res.message);
          }
        });
      }
    }
  });
};

const batchDelLineFun = ids => {
 
  confirmWarningMsg({
    msg:'是否确认删除?',
    callback: val => {
      if (val == "confirm") {
        getTariffBathDelApi({ type_id: paramsProp.typeId,ids: ids}).then(res => {
          if (res.code == ResultEnum.SUCCESS) {
            successMsg(proxy.$t("merak.delete_success"));
            initDataBool.value = true;
            nextTick(() => {
              initDataBool.value = false;
            });
          }
          if (res.code == ResultEnum.ERROR) {
            failMsg(res.message);
          }
        });
      }
    }
  });
};

//#endregion

//#region 模板文件
//模版文件
const dialogTariff = ref(false);
const tariffTemplateFile = () => {
  dialogTariff.value = true;
};

const drawerCloseDialog = obj => {
  dialogTariff.value = false;
  if (obj.type == "refresh") {
    initDataBool.value = true;
    nextTick(() => {
      initDataBool.value = false;
    });
  }
};
//#endregion

//#region 高级搜索

const searchBarRef = ref(null);
const searchFormRef = ref(null);
const searchformData = ref({});
const searchDataArr = ref(null);
console.log(searchformData);
const getSearchItem = type_id => {
 
  getTariffSearchItemApi({type_id:type_id},props.type).then((res)=>{
      console.log(res)
      let {code,data,message,auth_list} =res;
      paramsProp.authArr=auth_list;
      if(code==ResultEnum.SUCCESS){
           searchDataArr.value = data;
           initSearchData();
      }else{
        failMsg(message);
      }
  })
 
};
const initSearchData = () => {
  let searchDataArrClone = JSON.parse(JSON.stringify(searchDataArr.value));
  let newSearchObj = {};
  if (searchDataArrClone && searchDataArrClone.length) {
    searchDataArrClone.map(dItem => {
      dItem.value = "";
      newSearchObj[dItem.key] = dItem;
    });
    searchformData.value=newSearchObj;
 
  }
};

//搜索
const submitForm = async (formEl: FormInstance | undefined) => {
  let searchObj = searchBarRef.value.formParams("value");
  paramsProp.params = { ...searchObj };
  searchBarRef.value?.clear();
  searchBarRef.value?.modalHide();
};
const searchFn = e => {
  if (props.type == "foodGoods") {
    paramsProp.params = { ...{ hs_code_cn: e.search } };
  } else {
    paramsProp.params = { ...{ hs_code: e.search } };
  }
};
//重置
const closeModal = () => {
  paramsProp.params = {hs_code:''};
  searchFormRef.value?.resetFields();
  searchBarRef.value?.modalHide();
  searchBarRef.value?.clear();
  initSearchData();
};
//#endregion

//#region 树结构
const treeState = reactive<{
  data: TreeType[];
  value?: string;
  title?: string;
  filter?: any;
}>({ data: [] });
const defaultKeys = ref([]); //默认选中数组
const expandedKeys = computed(() => {
  const arr: string[] = [];
  const arr1: string[] = [];

  if (!!route.query.key) {
    const routeKeys = route.query.key.toString().split("-");
    initFunJudge(routeKeys[1]);

    arr.push(routeKeys[0]);
    arr1.push(route.query.key.toString());
  } else {
    if (treeState.data.length) {
      let keys = treeState.data[0].childs[0]?.id.split("-");
      arr.push(keys[0]);
      initFunJudge(keys[1]);

      arr1.push(treeState.data[0].childs[0]?.id);
    }
  }
  defaultKeys.value = arr1; //设置默认值
  return arr;
});
const initFunJudge = key => {
    initDataBool.value = true;
    nextTick(() => {
      initDataBool.value = false;
    });
  paramsProp.typeId = key;
};
const handleCurrentChange: InstanceType<typeof ElTree>["onCurrent-change"] = (data, treeNode) => {
  console.log(data);
  console.log(treeNode);
  if (!treeNode.isLeaf) return;
  const url = new URL(location.href);
  url.searchParams.set("key", data.id.toString());
  // 记录浏览器参数
  history.pushState({}, "", url);
  treeRef.value?.setCheckedKeys([data.id]);
  //点击更改参数
  initFunJudge(data.id.toString().split("-")[1]);
  getSearchItem(data.id.toString().split("-")[1]);
};

const getTariffTree = () => {
  if (props.type == "foodGoods") {
    //食品默认42,不显示左侧树结构
    initFunJudge("42");
      getSearchItem(42);
  } else {
    getTariffTreeApi({ type: props.type }).then(res => {
      
      let { code, data } = res;
      if (code == ResultEnum.SUCCESS) {
        console.log(data);
        const generate = (list: TreeType[], parentId?: string | number) => {
          const arr: TreeType[] = [];
          list.forEach(item => {
            const payload: TreeType = {
              id: `${!!parentId ? parentId + "-" : ""}${item.value}`,
              value: item.value,
              label: item.label,
              set: item.set
            };
            if (!!item.childs?.length) {
              payload.childs = generate(item.childs, item.value);
            }
            arr.push(payload);
          });
          return arr;
        };
        treeState.data = [...generate(data)];
        initTreeBool.value=true;
        if (!!route.query.key) {
          getSearchItem(route.query.key.toString().split("-")[1]);
        } else {
          getSearchItem(treeState.data[0].childs[0]?.id.split("-")[1]);
        }
      }
    });
  }
};
//#endregion

onMounted(() => {
  getTariffTree();
});
</script>
<style lang="scss" scoped>
.tariffCont {
  height: 100%;
}
.left_tree {
  display: flex;
  flex-direction: column;

  & > :not(:first-child) {
    margin-top: var(--merak-space);
  }
  .title {
    font-size: 16px;
  }
}
.el-tree {
  :deep(.el-tree-node.is-checked .el-tree-node__content:has(.is-leaf)) {
    color: #fff !important;
    background-color: var(--el-color-primary) !important;
  }
}
</style>
